<template>
  <div>
    <div class="title">
      <span>全部业务经理</span>
      <div>
        <el-button type="primary" @click="newBusiness">新增业务经理</el-button>
        <el-button icon="el-icon-refresh" @click="refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <div class="block">
              <el-date-picker v-model="serviceinfo.stardate" type="datetime" placeholder="提交起始时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
              <el-date-picker v-model="serviceinfo.enddate" type="datetime" placeholder="提交结束时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </div>
          </div>
          <div class="leftitem">
            <div class="block">
              <el-input class="merchants" v-model.trim="serviceinfo.head" v-if="rolesId !== 3" placeholder="服务商名称/编号" @keyup.enter.native="soso"></el-input>
            </div>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
            <el-input class="merchants" v-model.trim="serviceinfo.agent" placeholder="业务员姓名/编号" @keyup.enter.native="soso"></el-input>
            <el-input class="merchants" v-model.trim="serviceinfo.phone" placeholder="业务员手机号" @keyup.enter.native="soso"></el-input>
          </div>
          <div class="rightitem" v-if="rolesId == 1 || rolesId == 2 || rolesId == 8 || rolesId == 9">
            <el-form label-width="80px">
              <el-autocomplete class="merchants" v-model.trim="tagname" :fetch-suggestions="querySearch_tag" @select="serviceid_tag" placeholder="标签名" :trigger-on-focus="false"></el-autocomplete>
            </el-form>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso" :disabled="isDisable">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          :loading="loading" 
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
        >
           <el-table-column type="index" align="center" width='50' label="序号"></el-table-column>
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="code" align="center" label="编号"></el-table-column>
          <el-table-column prop="name" align="center" label="姓名"></el-table-column>
          <el-table-column prop="phone" align="center" label="手机号"></el-table-column>
          <el-table-column prop="idnum" align="center" label="身份证号"></el-table-column>
          <el-table-column prop="createtime" align="center" label="创建时间"></el-table-column>
          <el-table-column prop="agentName" align="center" label="所属服务商"></el-table-column>
          <el-table-column prop="subMerchantNum" align="center" label="签约商户数(个)"></el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="joinbdinfo(scope.row)">详情</el-button>
              <el-button type="text" size="small" @click="deleteServiceProviders(scope.row.id)">注销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-sizes="[10,20,30,40,50]"
            :page-size="cur_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>

       <!-- 新增业务经理 -->
      <el-dialog v-dialogDrag title="新增业务经理" :visible.sync="visible" width="30%" :close-on-click-modal = "false">
        <el-form
          :model="addBD"
          status-icon
          ref="addBD"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item :required="true" label="业务经理名称" >
           <el-input type="text" v-model.trim="addBD.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="手机号">
            <el-input type="text" v-model.trim="addBD.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="身份证号">
            <el-input type="text" v-model.trim="addBD.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="所属服务商">
            <el-autocomplete class="select-input" v-model.trim="agentname" :fetch-suggestions="querySearch_fws" @select="serviceid_fws" placeholder="请输入服务商名称" :trigger-on-focus="false"></el-autocomplete>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="addBDfun()">确定</el-button>
        </span>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import { getBdList, getUserSelect, getLastService, addBdManager, deleteBD, getlabelTagList, getDimensionTagList } from "@/api/api";
export default {
  name: "baseform",
  data: function() {
    return {
      loading: true,
      isDisable: false,
      inputName:'',
      restaurants:[],
      lastservice:[],//获取服务商数据
      cur_page: 1,
      cur_size: 10,
      total1:0,
      multipleSelection: [],
      merchantarr:[],
      pageCount:"",
      visible:false,
      serviceinfo:{
        stardate:"",
        enddate:"",
        head:"",
        phone:"",
        agent:""
      },
      addBD:{},
      dimension:'',//选择维度
      tagname:'',//标签名
      label_all:[],//标签模糊查询
      tagId:'',
      agentname:'',
      agent_id:''
    };
  },
  created() {
    this.getPermissions()
    this.getBdList()
  },
  mounted() {
  
  },
  methods: {
     //修改thead 背景色
     tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;'
      }
    },
    //获取权限
    getPermissions(){
      var aaa = sessionStorage.getItem('userInfo')
      var bbb = JSON.parse(aaa)
      this.rolesId = bbb.rolesId
      // this.serviceinfo.state = this.rolesId
      // this.fid = bbb.fid
    },
    //服务商搜索模糊查询
    // querySearch(queryString, cb) {
    //   var restaurants = this.restaurants;
    //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
    //   // 调用 callback 返回建议列表的数据
    //   cb(results);
    //   getUserSelect({ //商户模糊查询
    //     roleId: 5,
    //     keywords: this.inputName
    //   }).then(res => {
    //     console.log(res.data)
    //     if(res.code == 200){
    //       if(this.restaurants.length == 0){
    //         for(var i=0;i<res.data.length;i++){
    //           this.restaurants.push({'value':res.data[i].fname,'id':res.data[i].fid})
    //         }
    //       }
    //     }
    //   })
    // },
    querySearch_fws(queryString,cb){
      let that = this
      getLastService({
        type:2,
        keywords: this.agentname
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          this.$router.push('/login');
        }else if(res.code == 200){
          that.lastservice = []
          for(var i = 0; i < res.data.rows.length; i++){
            that.lastservice.push({"id":res.data.rows[i].id,"value":res.data.rows[i].agentname})
          }
          let servicearr = that.lastservice;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    serviceid_fws(item){
      this.agent_id = item.id
    },
    onSubmit() {
      this.$message.success("提交成功！");
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1])
      ]);
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.getBdList()
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });
    },
     // 分页数量
    sizechange(val){
      this.cur_size = val
      this.getBdList()
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });
       
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    joinbdinfo(val) {
      this.$router.push({ 
        path: "/bdinfo",
        // query: { 
        //     no: val,
        // } 
      });
      sessionStorage.setItem('bdlist_id',JSON.stringify(val.id))
      sessionStorage.setItem('bdlist_agentname',JSON.stringify(val.name))
    },
    // 门店列表
    getBdList(){
       this.isDisable = true
       getBdList({
          page: this.cur_page,
          size: this.cur_size,
          startTime: this.serviceinfo.stardate,
          endTime: this.serviceinfo.enddate,
          keywords: this.serviceinfo.agent,
          searchwords: this.serviceinfo.head,
          phone: this.serviceinfo.phone,
          tagId: this.tagId
        }).then(res => {
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else{
            this.loading = false
            this.isDisable = false
            this.merchantarr = res.data
            this.pageCount = res.pageInfo.pageCount
            this.total1 = res.pageInfo.recordCount
          }
        });
    },
    // 搜索
    soso(){
      this.cur_page = 1
      this.getBdList()
    },
    // 重置
    reset(){
      this.serviceinfo.head = ''
      this.serviceinfo.phone = ''
      this.serviceinfo.stardate = ''
      this.serviceinfo.enddate = ''
      this.serviceinfo.agent = ''
      this.dimension = ''
      this.tagname = ''
      this.tagId = ''
    },
    // 刷新
    refresh (){
      // location.reload()
      // this.$router.replace({
      //   path: '/refresh',
      //   query: {
      //     t: Date.now()
      //   }
      // })
      this.loading = true
      this.channellist()
    },
    //新增业务经理获取服务商下拉列表
    newBusiness(){
      this.visible = true
      this.addBD = {}
      // getLastService({
      //   type:2
      // }).then(res => {
      //   if(res.code == 405){
      //     sessionStorage. removeItem('token')
      //     this.$router.push('/login');
      //   }else if(res.code == 200){
      //     this.lastservice = []
      //     for(var i = 0; i < res.data.rows.length; i++){
      //       this.lastservice.push({value:res.data.rows[i].id,label:res.data.rows[i].agentname})
      //     }
      //   }
      // })
    },
    //删除服务商
    deleteServiceProviders(v){
      this.$confirm(`是否确定注销该账号？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(() => {
          deleteBD({},v).then(res => {
            if(res.code == 405){
                sessionStorage. removeItem('token')
                this.$router.push('/login');
              }else if(res.code == 200){
                this.$message({
                  message: '注销成功',
                  type: 'success'
                });
                this.getBdList()
              }else{
                this.$message.error(res.message);
              }
          })
      })
      .catch(() => {
          this.$message({
              type: "info",
              message: "已取消"
          });
      });
    },
    // 新增bd按钮
    addBDfun(){
      addBdManager({
        name: this.addBD.name,
        phone: this.addBD.phone,
        idnum: this.addBD.address,
        agentid: this.agent_id
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          this.$router.push('/login');
        }else if(res.code == 200){
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.visible = false
          this.addBD.name = ''
          this.addBD.phone = ''
          this.addBD.address = ''
          this.agent_id = ''
          this.agentname = ''
          this.getBdList()
        }else{
          this.$message.error(res.message);
        }
      })
    },
    //维度查询标签
    // dimension_menu(v){
    //   this.label_all = []
    //   getDimensionTagList({
    //     roleId: v
    //   }).then(res => {
    //     if(res.code == 405){
    //       sessionStorage. removeItem('token')
    //       this.$router.push('/login');
    //     }else if(res.code == 200){
    //       for(var i=0;i<res.data.length;i++){
    //         this.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
    //       }
    //     }else{
    //       this.$message.error(res.message);
    //     }
    //   })
    // },
    //标签模糊
    querySearch_tag(queryString,cb){
      let that = this
      getDimensionTagList({
        roleId: 4,
        tagwords: this.tagname
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          that.$router.push('/login');
        }else if(res.code == 200){
          that.label_all = []
          for(var i=0;i<res.data.length;i++){
            that.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
          }
          let servicearr = that.label_all;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          that.$message.error(res.message);
        }
      })
    },
    serviceid_tag(item){
      console.log(item)
      this.tagId = item.id
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
  }
};
</script>
<style scoped lang="less">
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #00152a;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  width: 50%;
  text-align: center;
  line-height: 200%;
}
.tableBox {
  margin-top: 20px;
}

.red {
  color: #f9607d;
}
.block{
  width: 100%;
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
.select-input{
  width: 100%;
}
</style>